package com.nuanshui.heatedloan.extension.interceptor;

import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.heatedloan.controller.dubbo.transform.ConnectDubbo;
import com.nuanshui.heatedloan.extension.annotation.OrganizationUserSafeToken;
import com.nuanshui.heatedloan.userinfo.model.SimpleUserInfo;
import com.nuanshui.heatedloan.userinfo.model.User;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;

public class OrganizationInterceptor implements HandlerInterceptor {
	protected Logger log = LoggerFactory.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		boolean result = false;
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			OrganizationUserSafeToken userSafeToken = handlerMethod.getMethod().getAnnotation(OrganizationUserSafeToken.class);
			if (userSafeToken == null)
				return true;
			ConnectDubbo connectDubbo = SpringContextUtil.getBean(ConnectDubbo.class);
			User user = getCurrentUser(request, connectDubbo);
			if (!result) {
				throw new BizException(GlobalErrorCode.UNKNOWN, "你已被移除组织架构");
			}
		} else if (handler instanceof CorsConfigurationSource) { //如果是跨域...
			return true;
		}

		return result;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

	public User getCurrentUser(HttpServletRequest request, ConnectDubbo connectDubbo) {
		String callback = request.getHeader("channel");

		if (callback == null)
			log.info("该用户不来自微信！");
		if ("weixin".equals(callback)) {// 表示是微信客户端的调用
			String userId = request.getHeader("userId");
			log.info("当前用户来自微信" + "userId=" + userId);
			SimpleUserInfo simpleUserInfo = connectDubbo.getSimpleUserInfo(userId);
			if (simpleUserInfo != null) {
				User user = new User();
				try {
					BeanUtils.copyProperties(user, simpleUserInfo);
					return user;
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		} else {
			Authentication auth = SecurityContextHolder.getContext().getAuthentication();
			if (auth != null) {
				Object principal = auth.getPrincipal();
				if (principal instanceof User) {
					User user = (User) principal;
					if (user != null && !user.isAnonymous()) {
						return user;
					}
				}

				if (auth.getClass().getSimpleName().indexOf("Anonymous") < 0) {
					log.error("Unknown authentication encountered, ignore it. " + auth);
				}
			}
		}

		User empty = new User();
		empty.setId("");
		return empty;
	}

}
